﻿using QDAS;
using QDasTransfer.Forms;
using System;
using System.Globalization;
using System.IO;
using System.Text;

using static QDasTransfer.Common;

namespace QDasTransfer.Transducer
{
	/// <summary>
	/// 2020/07/27 新建联合汽车电子（UAES）一厂新EP530转换器
	/// 注：需要在config.ini 配置 ConvertID=T202002
	/// </summary>
	public class T202004_UAES1_Matrix : ConvertBase
	{
		public T202004_UAES1_Matrix()
		{
			CompanyName = "联合汽车电子一厂Matrix转换器";
			Version = "1.0.1 (2021/01/19)";
			Extensions = "xls.xlsx";
		}

		/// <summary>
		/// 核心转换函数，将输入EXCEL文件(inpath)转换为输出DFQ文件(inpath)。
		/// </summary>
		/// <param name="inpath">输入EXCEL文件(inpath)</param>
		/// <param name="outpath">输出DFQ(outpath)</param>
		/// <returns></returns>
		public override bool Convert(string inpath, string outpath)
		{
			var form = new K1086Form();
			form.ShowDialog();

			string k1086 = form.K1086;
			string k0053 = form.K0053;

			/*********************** 1. 数据加载 *************************/
			var sheet = LoadWorkSheet(inpath, "Protokoll");
			if (sheet == null)
			{
				Error("表单加载失败。");
				return false;
			}

			/*********************** 2. 数据转换模块 *************************/
			try
			{
				var inputType = sheet["D10"].Value.Trim().ToLower(); 
				QFile qf = new QFile();
				string cols = "";
				if (inputType == "e")
				{
					cols = "HIOYZ";
				}
				else if (inputType == "c")
				{
					cols = "HK";
				}

				if (string.IsNullOrEmpty(cols))
					return false;
				
				qf[1001] = sheet["C4"].Value.Split('-')[0];
				if(!string.IsNullOrEmpty(k1086))
					qf[1086] = k1086;
				for (int col = 0; col < cols.Length; col++)
				{
					char ch = cols[col];
					var qch = qf.AddQCharacteristic();
					DateTime date = DateTime.Parse(sheet["C3"].Value);
					// string k0053 = Path.GetFileNameWithoutExtension(inpath).Split('-')[0];
					qch[2002] = GetSheetValue(sheet, ch + "14")?.Replace("\r\n", "").Replace("\n", "");
					for (int i = 15; i < sheet.Rows.Length; i++)
					{
						if (sheet[$"{ch}{i}"].Value?.Trim().Length > 0)
						{
							var qdata = qch.AddItem();
							qdata.SetValue(GetSheetValue(sheet, ch + "" + i));//].FormulaValue);
							qdata.date = date;
							qdata[0053] = k0053;
						}
						else
						{
							// Console.WriteLine("empty and return");
							break;
						}
					}
				} 
				qf.ToDMode(); 
				File.WriteAllText(outpath, qf.GetKString(), Encoding.UTF8);
				sheet.Dispose();
				sheet = null;
				return true;
			}
			catch (Exception ex1)
			{
				Error("转换失败，原因： " + ex1.Message);
			}

			return false;
		}

		private string GetSheetValue(Spire.Xls.Worksheet sheet, string range)
		{
			if (sheet == null)
				return null; 
			return sheet[range].HasFormula ? sheet[range].FormulaValue.ToString() : sheet[range].Value;
			 
 

		}
	}
}
